package com.avic.tools.utils;

import java.nio.file.*;
import java.util.concurrent.TimeUnit;


/**
 * FileWatchService
 *
 * @author eomer
 * @date 22/5/6 14:26
 */
public class FileWatchService {

    /**
     * 对文件夹的实时监控
     * @param baseDir
     * @return void
     * @Date 22/5/6 14:29
     * @auther eomer
     */
    public static void nioDir(String baseDir){
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Paths.get(baseDir).register(watchService,
                    StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                    StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
            while (true) {
                WatchKey key = watchService.poll(2, TimeUnit.SECONDS);
                if (key == null) {
                    continue;
                }
                for (WatchEvent event : key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    Path path = (Path) (event.context());
                    Path fullPath = Paths.get(baseDir, path.toString());
                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("Create receving File:  " + fullPath.toString());
                    } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("Delete receving File:  " + fullPath.toString());
                    } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("Modefy receving File:  " + fullPath.toString());
                    } else if (kind == StandardWatchEventKinds.OVERFLOW) {
                        System.out.println("Overflow receving File:  " + fullPath.toString());
                    }
                }
                key.reset();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String baseDir = "D:\\dev";
        nioDir(baseDir);
    }

}